package com.general.framework.qinyi.event.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class EventConfig {
    /**
     * 开启异步
     */
    @Bean("eventAsyncTaskExecutor")
    public Executor getAsyncExecutor() {
        int cpuCount = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(cpuCount * 2);
        threadPoolTaskExecutor.setMaxPoolSize(cpuCount * 4);
        threadPoolTaskExecutor.setQueueCapacity(100);
        threadPoolTaskExecutor.setThreadNamePrefix("event-");

        // 线程池对拒绝任务（无线程可用）的处理策略，目前只实现了AbortPolicy、CallerRunsPolicy和DiscardPolicy，默认为后者，即丢弃任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());

        // 当任务被提交时，会进入到队列中，等待线程池中的任务执行完毕，才会优雅地关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);

        // 等待任务在shutdown时完成的时间，默认为0，即立即终止
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);

        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
